module SortHelper
	
	# Returns a hash for all sort options with their respective sort URLs
	def sort_urls(sort_options)
		Hash[sort_options.map { |so| [so[:name], sort_url(so[:id], so[:direction])] }]
	end
	
	# Returns an URL with the params to sort by the given column and direction.
	def sort_url(column, direction)
		url_for(params: {sort_by: column, direction: direction, page: nil})
	end
	
	def sort_order(default_column='', model=nil, default_direction='asc')
		sort_column(default_column, model) + ' ' + sort_direction(default_direction)
	end
  
	# Returns the column to sort by, correctly formatted to use in the order clause.
	def sort_column(default='', model=nil)
		# Protect against malicious user input -- only accept what's defined in the options!
		if sort_options.any? { |so| so[:id] == params[:sort_by] } 
			column = params[:sort_by]
		else
			column = default
		end
		
		if model != nil and column.include? '#'
			column.gsub('#', model.name.pluralize)
		else
			column
		end
	end

	# Sanitized against SQL-injection. Only allow "asc" or "desc" as parameter
	def sort_direction(default_direction='asc')
		%w[asc desc].include?(params[:direction]) ? params[:direction] : default_direction
	end
	
end
